package com.boxuegu.boxueguapiservice.controller;


import com.boxuegu.boxueguapiservice.entity.User;
import com.boxuegu.boxueguapiservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Vincent
 */
@RestController
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserService userService;
  
  /**
   * 用户注册
   *
   * @param user 用户名和用户密码
   * @return 注册是否成功
   */
  @PostMapping("/save")
  @ResponseBody
  public Map<String, Object> regist(@RequestBody User user) {
    HashMap<String, Object> map = new HashMap<>();
    int result;
    try {
      result = userService.savaUser(user);
    } catch (DuplicateKeyException d) {
      result = 0;
    }
    if (result == 1) {
      map.put("msg", "注册成功");
      map.put("success", true);
    } else {
      map.put("msg", "注册失败");
      map.put("success", false);
    }
    return map;
  }
  
  /**
   * 用户登录
   *
   * @param param 用户名和密码
   * @return 是否登录成功, 及用户实体
   */
  @PostMapping("/login")
  @ResponseBody
  public Map<String, Object> login(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    User user = userService.findOneByUserNameAndUserPassword(param);
    if (user != null) {
      map.put("msg", "登录成功");
      map.put("success", true);
      map.put("user", user);
    } else {
      map.put("msg", "登录失败");
      map.put("success", false);
    }
    return map;
  }
  
  /**
   * 修改密码
   *
   * @param param (用户id,原始密码oldPassword,新密码newPassWord)
   * @return 修改是否成功
   */
  @PostMapping("/updatePassWord")
  @ResponseBody
  public Map<String, Object> updatePassWord(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    Integer id = (Integer) param.get("id");
    String oldPassword = (String) param.get("oldPassword");
    User user = userService.findOneById(id);
    if (oldPassword.equals(user.getUserPassword())) {
      int i = userService.updatePassWord(param);
      if (i == 1) {
        map.put("msg", "成功");
        map.put("success", true);
      } else {
        map.put("msg", "失败");
        map.put("success", false);
      }
    } else {
      map.put("msg", "原始密码错误");
      map.put("success", false);
    }
    return map;
  }
  
  /**
   * 修改用户信息: 修改性别,修改昵称,修改签名
   *
   * @param user 用户信息
   * @return 修改是否成功
   */
  @PostMapping("/updateUser")
  @ResponseBody
  public Map<String, Object> updateUser(@RequestBody User user) {
    Map<String, Object> map = new HashMap<>();
    int i = userService.updateUser(user);
    if (i == 1) {
      map.put("msg", "成功");
      map.put("success", true);
    } else {
      map.put("msg", "失败");
      map.put("success", false);
    }
    return map;
  }
}
